import constantRouterMap from "@/router/constantRoutes";
import asyncRouterMap from "@/router/asyncRoutes";
import authority from "@/utils/authority";

function hasMenu(name, menu) {
  const { alias } = menu.meta || {};
  const menus = alias ? [alias, menu.name] : [menu.name];
  return menus.includes(name);
}
// 过滤有权限的路由
function permissionMenu(routerMap) {
  const { menu = [] } = authority.get() || {};
  return routerMap.filter(item => {
    const hasPermission = menu.find(it => hasMenu(it, item));
    if (hasPermission && item.children && item.children.length) {
      item.children = permissionMenu(item.children);
    }
    return hasPermission;
  });
}
function getRouter() {
  const { is_admin = false } = authority.get() || {};
  let addRouters = [];

  // 获取当前角色所有权限的路由菜单
  const permissionRouter = () => {
    let routers = [];
    if (is_admin) {
      addRouters = asyncRouterMap;
      routers = constantRouterMap;
      const target = routers.find(it => it.path === "/");
      target.children = [...target.children, ...addRouters];
    } else {
      addRouters = permissionMenu(asyncRouterMap);
      routers = constantRouterMap;
      const target = routers.find(it => it.path === "/");
      target.children = [...target.children, ...addRouters];
    }
    return routers;
  };

  const routers = permissionRouter();

  return {
    routers,
    addRouters
  };
}
const { routers, addRouters } = getRouter();

const permission = {
  state: {
    routers,
    addRouters,
    bannerRouteMaps: [],
    // banner自定义routers
    customRoutes: ["/shop", "/hotel"]
  },
  mutations: {
    SET_PERMISSION_ROUTER(state) {
      const { routers, addRouters } = getRouter();
      state.routers = routers;
      state.addRouters = addRouters;
    },
    UPDATE_ROUTER_MAP(state, router) {
      const { children } = router;
      state.bannerRouteMaps = children;
    },
    UPDATE_ROUTER_CUSTOM(state, router) {
      state.customRoutes = router;
    }
  },
  actions: {}
};

export default permission;
